package com.example.design.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.example.design.ordermanagement.state.OrderState;
import com.example.design.pojo.Order;
import com.example.design.sercive.OrderService;
import com.example.design.sercive.decorator.OrderServiceDecorator;
import com.example.design.utils.Constants;
import com.example.design.utils.RedisUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

@RestController
@RequestMapping("/order")
public class OrderController {

    //引入 Apollo 配置的服务级别
    @Value("${service.level}")
    private String serviceLevel;

    //引入装饰器
    @Resource
    private OrderServiceDecorator orderServiceDecorator;

    @Resource
    private OrderService orderService;

    @PostMapping("/create")
    public Order createOrder(@RequestParam String productId) throws Exception {
        return orderService.createOrder(productId);
    }

    @PostMapping("/pay")
    public String payOrder(@RequestParam String orderId, @RequestParam float price, @RequestParam Integer payType) {
        return orderService.getPayUrl(orderId, price, payType);
    }

    @PostMapping("/receive")
    public Order receive(@RequestParam String orderId) {
        return orderService.receiveOrder(orderId);
    }

    @PostMapping("/send")
    public Order send(@RequestParam String orderId) {
        return orderService.sendOrder(orderId);
    }

    //支付宝支付回调接口
    @RequestMapping("/alipaycallback")
    public String alipayCallback(HttpServletRequest request) throws UnsupportedEncodingException, AlipayApiException {
        //获取回调信息
        Map<String, String> params = new HashMap<>();
        Map<String, String[]> parameterMap = request.getParameterMap();
        for (Iterator<String> iterator = parameterMap.keySet().iterator(); iterator.hasNext(); ) {
            String name = iterator.next();
            String[] values = parameterMap.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
            }
            valueStr = new String(valueStr.getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);
            params.put(name, valueStr);
        }
        //验证签名，确保回调接口真的是支付宝平台触发的
        boolean signVerified = AlipaySignature.rsaCertCheckV1(params, Constants.ALIPAY_PUBLIC_KEY, "UTF-8", Constants.SIGN_TYPE);
        //确保是支付宝平台发起的回调
        if (signVerified) {
            // 商户订单号
            String out_trade_no = new String(request.getParameter("out_trade_no").getBytes(StandardCharsets.ISO_8859_1), "UTF-8");
            System.out.println("==========" + out_trade_no);
            // 支付宝流水号
            String trade_no = new String(request.getParameter("trade_no").getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);
            // 支付金额
            float total_amount = Float.parseFloat(new String(request.getParameter("total_amount").getBytes(StandardCharsets.ISO_8859_1), "UTF-8"));
            //进行相关业务操作,修改订单状态为待发货状态
            //Order order = orderService.payOrder(out_trade_no);
            Order order = orderServiceDecorator.decoratorPay(out_trade_no, Integer.parseInt(serviceLevel), total_amount);
            return "支付成功页面跳转，当前订单为" + order;
        } else {
            throw new UnsupportedOperationException("签名验证失败");
        }

    }


    @PostMapping("/friendPay")
    public void friendPay(@RequestParam String sourceCustomer, @RequestParam String orderId, @RequestParam String targetCustomer, @RequestParam String payResult, @RequestParam String role) {
        orderService.friendPay(sourceCustomer, orderId, targetCustomer, payResult, role);
    }
}
